package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.HexStrTransformUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

@Getter
@NoArgsConstructor
public class LineNumberTableAttribute extends AttributeInfo {
    private Integer lineNumberTableLength;
    private List<LineNumberTable> lineNumberTableList;

    public LineNumberTableAttribute(Integer attributeNameIndex, Integer attributeLength, Integer lineNumberTableLength, List<LineNumberTable> lineNumberTableList) {
        super(attributeNameIndex, attributeLength);
        this.lineNumberTableLength = lineNumberTableLength;
        this.lineNumberTableList = lineNumberTableList;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    public class LineNumberTable {
        private Integer startPc;
        private Integer lineNumber;
    }

    @Override
    protected LineNumberTableAttribute newAttributeInfo(Integer attributeNameIndex, Integer attributeLength, ClassFile classFile) {
        this.lineNumberTableLength = HexStrTransformUtil.parseHexToInt(classFile.readU2());
        this.lineNumberTableList = new ArrayList<>(lineNumberTableLength);
        for (int i = 0; i < lineNumberTableLength; i++) {
            Integer startPc = HexStrTransformUtil.parseHexToInt(classFile.readU2());
            Integer lineNumber = HexStrTransformUtil.parseHexToInt(classFile.readU2());
            lineNumberTableList.add(new LineNumberTable(startPc, lineNumber));
        }
        return this;
    }
}
